<template>
  <simple-table
    :left-btn-area-visible="false"
    :url-list="urlList"
    :current-use-btn-list="currentUseBtnList"
    :filed-property-list="filedPropertyList"
    :button-list="buttonList"
    submit-form-title="用户管理"
    @change-event="selectChangeEvent"
    @reset-submit-data="resetSubmitData"
    @reset-submit-form="resetSubmitForm"
    @reset-data-before-edit="resetDataBeforeEdit"
    @different-operation="differentOperation"
  ></simple-table>
  <el-dialog
    title="角色分配"
    v-model="roleDialogVisible"
    :close-on-click-modal="false"
  >
    <el-tree
      ref="roleTreeRef"
      :data="allRoleList"
      :props="roleTreeProps"
      node-key="id"
      show-checkbox
      highlight-current
      check-strictly
    ></el-tree>
    <template #footer>
      <el-button
        style="float: left"
        type="primary"
        @click="
          submitSetRole();
          changeRoleDialogVisible();
        "
        >确认
      </el-button>
      <el-button @click="changeRoleDialogVisible()">关闭</el-button>
    </template>
  </el-dialog>
  <el-dialog
    title="身份确认"
    v-model="resetPasswordVisible"
    :close-on-click-modal="false"
  >
    <el-form :model="resetPasswordForm" :rules="rules">
      <el-form-item label="当前用户" prop="name">
        <el-input v-model="resetPasswordForm.name" disabled />
      </el-form-item>
      <el-form-item label="当前密码" prop="password">
        <el-input
          v-model="resetPasswordForm.password"
          placeholder="请输入你的密码"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="confirmUser()">确认</el-button>
      <el-button @click="changePasswordVisible()">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import SimpleTable from "@/components/table/simple/SimpleTable.vue";
import Scope from "@/models/Scope";
import { TableUrl } from "@/models/TableSetting";
import { BtnNameEnum } from "@/components/table/simple/BtnNameEnum";
import { RoleDialogVisible } from "@/views/system/RoleDialogVisible";
import { UserManage } from "@/views/system/UserManage";
import { ElMessageBox } from "element-plus/es";
import api from "@/utils";
import { reactive, ref, Ref } from "vue";
import { ResetPassword } from "@/views/system/ResetPassword";
import FiledProperty from "@/models/FiledProperty";
import { RuleEnum } from "@/components/form/basic/FormEnum";
import { BaseFormItem } from "@/components/form/formItem/FormItemMeta";

const urlList = {
  refreshUrl: "/basic-request/user/search",
  modifyingSingleUrl: "/system/user",
  resetPasswordUrl: "/system/resetPassword",
  deleteUrl: "/basic-request/User/batch-delete",
} as TableUrl;
// 当前页面使用的功能按钮
const currentUseBtnList: BtnNameEnum[] = [
  BtnNameEnum.ADD,
  BtnNameEnum.REFRESH,
  BtnNameEnum.DELETE,
];
const filedPropertyList = reactive([
  {
    filedName: "username",
    label: "角色名称",
    span: 8,
    width: 200,
    minWidth: 120,
    showInTable: true,
    showInForm: true,
    showInSearch: true,
    formType: "el-form-text",
    rules: [
      {
        ruleName: RuleEnum.REQUIRED,
        ruleValue: true,
        message: "角色名称不能为空",
      },
    ],
  },
  {
    filedName: "authorityCode",
    label: "用户授权码",
    span: 8,
    width: 220,
    minWidth: 220,
    showInTable: true,
    showInForm: true,
    formType: "el-form-text",
    meta: {
      editDisabled: true, // 该属性编辑时不可以编辑
    },
  },
  {
    filedName: "queryCode",
    label: "查询授权码",
    span: 8,
    minWidth: 220,
    showInTable: true,
    showInForm: true,
    formType: "el-form-text",
    meta: {
      editDisabled: true, // 该属性编辑时不可以编辑
    },
  },
  {
    filedName: "password",
    label: "角色密码",
    span: 8,
    width: 200,
    minWidth: 120,
    showInTable: false,
    showInForm: false,
    formType: "el-form-text",
  },
  {
    filedName: "type",
    label: "用户类别",
    span: 8,
    width: 220,
    minWidth: 220,
    showInTable: true,
    showInForm: true,
    formType: "el-form-select-dropdown",
    rules: [
      {
        ruleName: RuleEnum.REQUIRED,
        ruleValue: true,
        message: "用户类别不能为空",
      },
    ],
    meta: {
      optionList: [
        { label: "内部员工", value: "内部员工" },
        { label: "外部员工", value: "外部员工" },
        { label: "其他用户", value: "其他用户" },
      ],
    },
  },
  {
    filedName: "staffNo",
    label: "员工工号",
    span: 16,
    width: 220,
    minWidth: 220,
    showInTable: true,
    showInForm: false,
    formType: "el-form-input-auto-select",
    meta: {
      searchUrl: "/basic-request/staff/search",
      inputProp: "no",
      selectProp: "name",
    },
  },
]) as Array<FiledProperty>;

const buttonList = [
  {
    label: "重置密码",
    name: "reset-password",
    icon: "Key",
    type: "text",
  },
  {
    label: "角色分配",
    name: "role-assignment",
    icon: "User",
    type: "text",
  },
];

// 角色弹窗的显示与隐藏
const { roleDialogVisible, changeRoleDialogVisible } = RoleDialogVisible();
// 重置密码弹窗
const { resetPasswordVisible, changePasswordVisible } = ResetPassword();

const {
  allRoleList,
  roleTreeRef,
  roleTreeProps,
  getAllRoleList,
  submitSetRole,
  currentUserIdAuthorization,
} = UserManage();
getAllRoleList();

// 重置密码身份确认表单
const resetPasswordForm = ref({});
// 重置密码表单校验规则
const rules = {
  name: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
  password: [{ required: true, message: "密码不能为空", trigger: "blur" }],
};
// 确认修改人身份，并重置密码
const confirmUser = () => {
  api.http
    .postJson(
      urlList.resetPasswordUrl +
        "/" +
        resetPasswordForm.value["password"] +
        "/" +
        resetPasswordForm.value["resetUserId"],
      {}
    )
    .then(() => {
      changePasswordVisible();
    })
    .catch((e) => {
      console.log(e);
    });
};

// 新增用户设置默认密码 修改提交时的数据
const resetSubmitData = (
  submitData: Ref,
  callback: (resetFrom: Record<string, unknown>) => void
) => {
  if (submitData["password"] === null) {
    submitData["password"] = "123456";
  }
  callback(submitData.value);
};

// 新增数据时格式化表单
const resetSubmitForm = () => {
  filedPropertyList.forEach((filed) => {
    if (filed.filedName == "staffNo") {
      if (filed.meta) filed.meta.optionList = [];
      filed.showInForm = false;
    }
  });
};

// 当下拉选择框数据变化时事件
const selectChangeEvent = async (val: string | unknown) => {
  await filedPropertyList.forEach((filed) => {
    if (filed.filedName == "staffNo") {
      filed.meta = { inputProp: "no", selectProp: "name" } as BaseFormItem;
      filed.meta.searchUrl = "";
      filed.showInForm = false;
      if (val == "内部员工") {
        filed.showInForm = true;
        filed.meta.searchUrl = "/basic-request/staff/search";
      }
      if (val == "外部员工") {
        filed.showInForm = true;
        filed.meta.searchUrl = "/basic-request/ExternalStaff/search";
      }
    }
  });
};

// 编辑之前格式控制显示与隐藏
const resetDataBeforeEdit = async (
  editForm: Ref,
  callback: (resetEditFrom: Record<string, unknown>) => void
) => {
  await filedPropertyList.forEach((filed) => {
    if (filed.filedName == "staffNo") {
      filed.showInForm = editForm.value.type != "其他用户";
    }
  });
  callback(editForm.value);
};
const differentOperation = (name: string, scope: Scope) => {
  switch (name) {
    case "role-assignment":
      currentUserIdAuthorization(scope);
      setTimeout(() => {
        changeRoleDialogVisible();
      }, 200);
      break;
    case "reset-password":
      console.log(scope.row);
      ElMessageBox.confirm(
        '确认重置用户 " ' + scope.row.username + ' "的密码？',
        "Warning",
        {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          resetPasswordForm.value["name"] = sessionStorage.getItem("token");
          resetPasswordForm.value["resetUserId"] = scope.row.id;
          changePasswordVisible();
        })
        .catch((err) => {
          console.log(err);
        });
      break;
  }
};
</script>
<style scoped></style>
